package com.nodecollege.cloud.common.model.vo;

import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.model.po.UpmsMenu;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 组织机构树
 *
 * @author LC
 * @date 2019/12/11 18:08
 */
@Data
public class MenuTreeVO extends UpmsMenu implements Comparable<MenuTreeVO> {
    /**
     * 子集
     */
    private List<MenuTreeVO> children;

    public MenuTreeVO() {
    }

    public MenuTreeVO(UpmsMenu menu) {
        super.setMenuId(menu.getMenuId());
        super.setMenuName(menu.getMenuName());
        super.setMenuCode(menu.getMenuCode());
        super.setMenuType(menu.getMenuType());
        super.setMenuSource(menu.getMenuSource());
        super.setIcon(menu.getIcon());
        super.setParentId(menu.getParentId());
        super.setAppId(menu.getAppId());
        super.setTenantId(menu.getTenantId());
        super.setPath(menu.getPath());
        super.setOpenType(menu.getOpenType());
        super.setApiId(menu.getApiId());
        super.setApplicationName(menu.getApplicationName());
        super.setApiUrl(menu.getApiUrl());
        super.setNum(menu.getNum());
        super.setState(menu.getState());
    }

    public static List<MenuTreeVO> getMenuTree(List<UpmsMenu> menuList) {
        return getMenuTree(menuList, 0L);
    }

    /**
     * 获取menuTree
     *
     * @return
     */
    public static List<MenuTreeVO> getMenuTree(List<UpmsMenu> menuList, Long pid) {
        List<MenuTreeVO> menuTreeList = new ArrayList<>();
        Iterator<UpmsMenu> menuIterator = menuList.iterator();
        while (menuIterator.hasNext()) {
            UpmsMenu menu = menuIterator.next();
            if (menu.getParentId().equals(pid)) {
                menuTreeList.add(new MenuTreeVO(menu));
                menuIterator.remove();
            }
        }
        Collections.sort(menuTreeList);
        for (MenuTreeVO menuTreeVO : menuTreeList) {
            menuTreeVO.setChildren(getMenuTree(menuList, menuTreeVO.getMenuId()));
        }
        if (menuTreeList.isEmpty()){
            return null;
        }
        return menuTreeList;
    }

    @Override
    public int compareTo(MenuTreeVO o) {
        return this.getNum().compareTo(o.getNum());
    }
}
